<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      let datas = [
        { id: "1", parent_id: "0", other: "113" },
        { id: "0", parent_id: "88", other: "456" },
        { id: "2", parent_id: "1", other: "456" },
      ];

      const handleDatas = (datas) => {
        let nodeMap = new Map();
        let result = [];

        // 为每个节点初始化 children 属性，并将节点添加到 Map 中
        datas.forEach((item) => {
          item.children = [];
          nodeMap.set(item.id, item);
        });

        // 构建父子关系
        datas.forEach((item) => {
          if (nodeMap.has(item.parent_id)) {
            nodeMap.get(item.parent_id).children.push(item);
          } else {
            // 如果没有找到父节点，说明当前节点是根节点
            result.push(item);
          }
        });

        return result;
      };

      const res = handleDatas(datas);
      console.log("res", res);
    </script>
  </body>
</html>
